<template>
  <div id="app" v-loading="loading">
    <el-button
      type="primary"
      icon="el-icon-circle-plus-outline"
      @click="add()"
      v-show="canEdit"
      >{{ addTitle }}</el-button
    >
    <el-table
      v-bind="{ ...tableConfig, data: tableData }"
      style="width: 100%; margin-top: 30px"
      type="expand"
      row-key="rowId"
      :expand-row-keys="expandRowKeys"
      @sort-change="sortChange"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form
            label-position="left"
            class="demo-table-expand"
            :label-width="labelWidth"
          >
            <el-form-item
              :label="`${item.title}:`"
              v-for="(item, index) in showColumn"
              :key="'column_' + index"
              class="form-item-part"
            >
              <div class="item-part">
                <template v-if="tableData[props.$index].edit">
                  <el-input
                    v-model="tableData[props.$index][item.prop]"
                    placeholder=""
                    v-if="
                      !item.hasOwnProperty('dataType') ||
                      item.dataType == 'text'
                    "
                  ></el-input>
                  <el-input
                    v-model="tableData[props.$index][item.prop]"
                    placeholder=""
                    type="textarea"
                    :autosize="{ minRows: 5}"
                    v-else-if="item.dataType == 'textarea'"
                  ></el-input>
                  <el-date-picker
                    v-model="tableData[props.$index][item.prop]"
                    type="date"
                    v-else-if="item.dataType == 'date'"
                    placeholder="选择日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>

                  <div v-else-if="item.dataType == 'upload'">
                    <el-button type="text" @click="clickShow(props.$index)">
                      点击上传文件
                    </el-button>
                    {{ tableData[props.$index][item.prop] }}
                  </div>
                </template>
                <template v-else>
                  {{ tableData[props.$index][item.prop] }}
                </template>
              </div>
            </el-form-item>
            <el-form-item
              :label="`${item}:`"
              v-for="(item, index) in slotArray"
              :label-width="labelWidth"
              :key="'column_solt' + index"
              class="form-item-part"
            >
              <slot
                :name="item"
                :scopeRow="props.row"
                :index="props.$index"
              ></slot>
            </el-form-item>
            <el-form-item
              :label="`操作`"
              :label-width="labelWidth"
              :key="props.$index"
              class="form-item-part"
              v-show="canEdit"
            >
              <el-button
                type="text"
                size="small"
                @click="edit(props.$index, true)"
                v-if="!tableData[props.$index].edit"
              >
                编辑
              </el-button>

              <el-popconfirm
                title="确定要保存吗"
                @confirm="edit(props.$index, false)"
                 v-if="tableData[props.$index].edit"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="small"
                
                >
                  保存
                </el-button>
              </el-popconfirm>
              <el-popconfirm
                title="确定要删除吗"
                @confirm="delOne(props.$index)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="small"
                  style="margin-left: 10px"
                 >删除</el-button
                >
              </el-popconfirm>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <!-- 上面为下拉模板 -->
      <el-table-column
        v-for="(item, index) in showColumn"
        :key="index"
        v-bind="{
          ...(item.hasOwnProperty('columnConfig') ? item.columnConfig : {}),
          width: item.width,
          label: item.title,
          prop: item.prop,
        }"
      >
        <template slot-scope="scope">
          <template v-if="tableData[scope.$index].edit">
            <el-input
              v-model="tableData[scope.$index][item.prop]"
              placeholder=""
              v-if="!item.hasOwnProperty('dataType') || item.dataType == 'text'"
            ></el-input>
            <el-input
              v-model="tableData[scope.$index][item.prop]"
              placeholder=""
              type="textarea"
              v-else-if="item.dataType == 'textarea'"
            ></el-input>
            <el-date-picker
              v-model="tableData[scope.$index][item.prop]"
              type="date"
              v-else-if="item.dataType == 'date'"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
            <div v-else-if="item.dataType == 'upload'" class="upload-part">
              <input
                :ref="fileChangeNum"
                @change="fileChange($event, item.prop)"
                title="点击上传"
                type="file"
                class="uploadInput"
              />
              <el-button
                type="text"
                class="uploadButton"
                @click="clickShow(scope.$index)"
              >
                点击上传文件
              </el-button>
              {{ tableData[scope.$index][item.prop] }}
            </div>
          </template>
          <template v-else>
            <span class="table-part">
              {{ tableData[scope.$index][item.prop] }}
            </span>
          </template>
        </template>
      </el-table-column>
      <el-table-column> </el-table-column>
              
      <el-table-column :label="'操作'" width="100" v-if="canEdit">
        <template slot-scope="{ $index }">
          <el-button
            type="text"
            size="small"
            @click="edit($index, true)"
            v-show="!tableData[$index].edit"
          >
            编辑
          </el-button>
          <el-popconfirm title="确定要保存吗" @confirm="edit($index, false)">
            <el-button
              slot="reference"
              type="text"
              size="small"
              v-show="tableData[$index].edit"
            >
              保存
            </el-button>
          </el-popconfirm>
          <el-popconfirm title="确定要删除吗" @confirm="delOne($index)">
            <el-button
              slot="reference"
              type="text"
              size="small"
              style="margin-left: 10px"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { uploading } from "@/utils/uploading";
import { mapActions } from "vuex";

export default {
  name: "app",
  components: {},
  props: {
    dataProps: {
      type: Array,
      default: () => {
        return [];
      },
    },
    addTitle: {
      type: String,
      default: "添加记录",
    },
    tableColumn: {
      type: Array,
      default: () => {
        return [];
      },
    },
    loading: {
      type: Boolean,
      default: false,
    },
    tableConfig: {
      type: Object,
      default: () => {
        return {};
      },
    },
    slotArray: {
      type: Array,
      default: () => {
        return [];
      },
    }, //插槽数组
    labelWidth: {
      type: String,
      default: () => {
        return "100px";
      },
    },
    fileChangeNum: {
      type: String,
      default: "fileChange",
    },
    mapping: {
      type: Object,
      default: () => {
        return {};
      },
    },
    canEdit:{
        type: Boolean,
        default: true,
    },
    buttonShow:{
      type: Array,
       default: () => {
        return ["save","delete"];
      },
    }
  },
  data() {
    return {
      tableData: [],
      originalData: [],
      columnSort: {
        order: null,
      },
      expandRowKeys: [],
      clickIndex: 0,
    };
  },
  created() {
    this.dataProps.forEach((item, index) => {
      item.rowId = index;
    });

    this.tableData = this.dataProps;
    this.originalData = this.dataProps;
  }, //生命周期 - 创建完成（可以访问当前this实例）
  mounted() {}, //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  watch: {
    // tableData(newValue,oldValue){
    //   alert()
    // }
    "tableData.length":function(newValue){
          this.$emit('lengthChange',newValue)
    }
  },
  computed: {
    addMod() {
      const mod = {};
      mod.edit = true;
      mod.rowId = this.tableData.length;
      this.tableColumn.forEach((item) => (mod[item.prop] = ""));
      return mod;
    },
    lastSource() {
      let tableData = this.tableData;
      for (let i = 0; i < tableData.length; i++) {
        delete tableData[i].edit;
      }
      return tableData;
    },
    showColumn() {
      let column = [];
      for (let i = 0; i < this.tableColumn.length; i++) {
        if (!this.tableColumn[i].notShow) {
          column.push(this.tableColumn[i]);
        }
      }
      return column;
    },
    // mappingReturnFiled(){
    //     // let prop = {}
    //     //  for(let key in )

    // }
  },
  methods: {
    ...mapActions("upload", ["uploadOneFile"]),
    add() {
      let tableData = JSON.parse(JSON.stringify(this.tableData));

      let addMod = JSON.parse(JSON.stringify(this.addMod));
      tableData.unshift(addMod);

      this.expandRowKeys.push(addMod.rowId);

      this.$set(this, "tableData", tableData);
      this.originalData = this.tableData;
    },
    edit(index, bool) {
      this.$set(this.tableData[index], "edit", bool);
      this.originalData = this.tableData;

      if (!bool) {
        // let formData = {};
        // this.tableColumn.forEach(
        //   (item) => (formData[item.prop] = this.tableData[index][item.prop])
        // );
        let formData = this.mappingLastSource(this.tableData[index]);
        if (this.tableData[index].id) {
          formData.id = this.tableData[index].id;
        }
        this.$emit("save", formData, index); //传出单条
        this.$emit("saveAll", this.mappingSaveAll()); //传出所有
      }
    },
    assignment(index, obj) {
      // console.log(index);
      // console.log(obj);

      // if()
      for (let key in obj) {
        if (this.tableColumn.findIndex((item) => item.prop == key) == -1) {
          this.tableColumn.push({ prop: key, notShow: true });
        }
      }

      this.$set(this.tableData, index, { ...this.tableData[index], ...obj });

      // console.log(this.tableData);
    },
    delOne(index) {
      let formData = {};
      formData.id = this.tableData[index].id;
      if (formData.id) {
        formData.delete_time = this.sysTime();

        this.$emit("save", formData);
        this.$emit("saveAll", this.mappingSaveAll());
      }
      this.tableData.splice(index, 1);
    },
    returnField() {
      //    let propArray =   this.tableColumn.map(item=>item.prop)

      return this.lastSource;
    },
    sortChange(column) {
      this.columnSort = column;
      this.sortOperation();
    },
    sortOperation() {
      let originalData = JSON.parse(JSON.stringify(this.originalData));
      this.tableData =
        this.columnSort.order != null
          ? this.bubblingSort(
              originalData,
              this.columnSort.prop,
              this.columnSort.order == "descending" ? "DESC" : "ASC"
            )
          : originalData;
    },
    clickShow(index) {
      this.clickIndex = index; //当前点击上传的index存起来
      this.$refs[this.fileChangeNum][index].click();
    },
    async fileChange(e, prop) {
      const loading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let file = e.target.files[0];
      let formData = uploading(file, "possess", "", "crm/possess", 100);
      if (formData) {
        let res = await this.uploadOneFile(formData);
        loading.close();
        if (res.code == 200) {
          this.$message.success({
            message: "文件上传成功",
            type: "success",
          });
          this.tableData[this.clickIndex][prop] = file.name;
          if (!this.mapping.hasOwnProperty(prop)) {
            this.$message({
              message: "缺少mapping对象传入的字段",
              type: "error",
            });
          }
          this.tableData[this.clickIndex][this.mapping[prop]] = res.data.url;
        }
      }
      this.$refs[this.fileChangeNum][this.clickIndex].value = "";
    },

    mappingSaveAll() {
      let lastSource = [];
      for (let i = 0; i < this.tableData.length; i++) {
        lastSource.push(this.mappingLastSource(this.tableData[i]));
      }
      return lastSource;
    },

    mappingLastSource(beforeObj) {
      let afterObj = {};
      let column = [
        ...this.tableColumn.map((item) => item.prop),
        ...Object.values(this.mapping),
      ];

      column.forEach((item) => (afterObj[item] = beforeObj[item]));
      return afterObj;
    },
    // fileUpload() {
    //  uploading()
    // },
  },
};
</script>
<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
  display: flex;
  flex-direction: column;
  flex: 1;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  flex: 1;
  padding-left: 45px;
  padding-right: 45px;
}
.table-part {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  // width: 50%;
}

.table-part {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.form-item-part {
  margin-top: 20px;
  margin-bottom: 20px;
  // border: 1px solid red;
  // overflow: hidden;
}
.uploadInput {
  // width: 300%;
  // height: 100%;
  // position: absolute;
  // top:0;
  // left:-100%;
  // opacity: 0;
  //  cursor: pointer;
  display: none;
}
.uploadButton {
  display: flex;
}
.upload-part {
  display: flex;
  flex-direction: column;
  // border: 1px solid red;
  justify-content: flex-start;
}
</style>
